using Microsoft.AspNetCore.Mvc;
using _RobotInspection.DTO;
using _RobotInspection.Models; // 修正命名空间
using _RobotInspection.Services;
using _RobotInspection.Interfaces;
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Threading.Tasks;
using _RobotInspection.Attributes;

namespace _RobotInspection.Controllers
{
    /// <summary>
    /// 点检计划管理控制器
    /// </summary>
    [ApiController]
    [Route("api/[controller]")]
    public class InspectionPlanController : ControllerBase
    {
        private readonly IInspectionPlanService _inspectionPlanService;

        public InspectionPlanController(IInspectionPlanService inspectionPlanService)
        {
            _inspectionPlanService = inspectionPlanService;
        }

        /// <summary>
        /// 获取所有公司及其机组（用于创建计划时选择）
        /// </summary>
        /// <returns></returns>
        [ApiStatus(ApiStatusEnum.Completed)]
        [HttpGet("company-with-crew")]
       
        public async Task<ActionResult<ApiResponse<List<EquipmentHierarchyDto>>>> GetCompanyWithCrew()
        {
            return await _inspectionPlanService.GetCompanyWithCrewAsync();
        }

        /// <summary>
        /// 根据ID获取指定设备的点检项
        /// </summary>
        /// <param name="id">设备ID</param>
        /// <returns></returns>
        [HttpGet("inspection-items")]
        [ApiStatus(ApiStatusEnum.Completed)]
        public async Task<ActionResult<ApiResponse<object>>> GetInspectionItems(long id)
        {
            return await _inspectionPlanService.GetInspectionItems(id);
        }
        /// <summary>
        /// 获取所有设备及其点检项（用于创建计划时选择）
        /// </summary>
        /// <returns></returns>
        [HttpGet("equipment-with-items")]
        public async Task<ActionResult<ApiResponse<List<EquipmentWithItemsDto>>>> GetEquipmentWithItems()
        {
            return await _inspectionPlanService.GetEquipmentWithItemsAsync();
        }

        /// <summary>
        /// 创建点检计划
        /// </summary>
        /// <param name="dto">点检计划创建信息</param>
        /// <returns></returns>
        [HttpPost("inspection-plan")]
        [ApiStatus(ApiStatusEnum.Testing)]
        public async Task<ActionResult<ApiResponse<long>>> CreateInspectionPlan([FromBody] CreateInspectionPlanDto dto)
        {
            return await _inspectionPlanService.CreateInspectionPlanAsync(dto);
        }

        /// <summary>
        /// 获取点检计划列表（分页）
        /// </summary>
        /// <param name="query">查询条件</param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<ApiResponse<PagedResult<InspectionPlanResponseDto>>>> GetInspectionPlans([FromQuery] InspectionPlanQueryDto query)
        {
            return await _inspectionPlanService.GetInspectionPlansAsync(query);
        }

        /// <summary>
        /// 根据ID获取点检计划详情
        /// </summary>
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        [HttpGet("{id}")]
        public async Task<ActionResult<ApiResponse<InspectionPlanResponseDto>>> GetInspectionPlanById([FromRoute] long id)
        {
            return await _inspectionPlanService.GetInspectionPlanByIdAsync(id);
        }

        /// <summary>
        /// 启用点检计划
        /// </summary>
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        [HttpPut("{id}/enable")]
        public async Task<ActionResult<ApiResponse<bool>>> EnableInspectionPlan([FromRoute] long id)
        {
            return await _inspectionPlanService.UpdatePlanStatusAsync(id, 1);
        }

        /// <summary>
        /// 禁用点检计划
        /// </summary>
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        [HttpPut("{id}/disable")]
        public async Task<ActionResult<ApiResponse<bool>>> DisableInspectionPlan([FromRoute] long id)
        {
            return await _inspectionPlanService.UpdatePlanStatusAsync(id, 0);
        }

        /// <summary>
        /// 删除点检计划
        /// </summary>
        /// <param name="id">计划ID</param>
        /// <returns></returns>
        [HttpDelete("{id}")]
        public async Task<ActionResult<ApiResponse<bool>>> DeleteInspectionPlan([FromRoute] long id)
        {
            return await _inspectionPlanService.UpdatePlanStatusAsync(id, 0);
        }

        /// <summary>
        /// 批量启用/禁用点检计划
        /// </summary>
        /// <param name="request">批量操作请求</param>
        /// <returns></returns>
        [HttpPut("batch-status")]
        public async Task<ActionResult<ApiResponse<object>>> BatchUpdatePlanStatus([FromBody] BatchUpdateStatusRequest request)
        {
            if (!ModelState.IsValid || request.PlanIds == null || request.PlanIds.Count == 0)
            {
                return BadRequest(ApiResponse<object>.Error("请求参数无效"));
            }

            int successCount = 0;
            int failCount = 0;

            foreach (var planId in request.PlanIds)
            {
                var action = await _inspectionPlanService.UpdatePlanStatusAsync(planId, request.IsActive);
                var api = (action.Result as OkObjectResult)?.Value as ApiResponse<bool>;

                if (api != null && api.Code == 200)
                {
                    successCount++;
                }
                else
                {
                    failCount++;
                }
            }

            return Ok(ApiResponse<object>.Success(
                new { SuccessCount = successCount, FailCount = failCount },
                $"批量操作完成：成功 {successCount} 个，失败 {failCount} 个"
            ));
        }

        /// <summary>
        /// 根据机组查询点检计划列表
        /// </summary>
        /// <param name="unit">机组名称</param>
        /// <param name="planType">点检周期类型（可选）：1-日点检，2-周点检，3-月点检，4-一次性点检</param>
        /// <returns></returns>
        [HttpGet("by-unit")]
        [ApiStatus(ApiStatusEnum.Deprecated)]
        public async Task<ActionResult<ApiResponse<List<InspectionPlanByUnitDto>>>> GetInspectionPlansByUnit([FromQuery] string unit, [FromQuery] byte? planType = null)
        {
            return await _inspectionPlanService.GetInspectionPlansByUnitAsync(unit, planType);
        }

        /// <summary>
        /// 分页查询点检计划
        /// </summary>
        /// <param name="queryDto">查询条件</param>
        /// <returns></returns>
        [HttpGet("paged")]
        [ApiStatus(ApiStatusEnum.Completed)]
        public async Task<ActionResult<ApiResponse<InspectionPlanPagedResultDto>>> GetInspectionPlansPaged([FromQuery] InspectionPlanPagedQueryDto queryDto)
        {
            return await _inspectionPlanService.GetInspectionPlansPagedAsync(queryDto);
        }

      
      
    }

    /// <summary>
    /// 批量更新状态请求
    /// </summary>
    public class BatchUpdateStatusRequest
    {
        /// <summary>
        /// 计划ID列表
        /// </summary>
        [Required(ErrorMessage = "计划ID列表不能为空")]
        public List<long> PlanIds { get; set; } = new List<long>();

        /// <summary>
        /// 目标状态：1-启用，0-禁用
        /// </summary>
        [Required(ErrorMessage = "状态值不能为空")]
        [Range(0, 1, ErrorMessage = "状态值必须为0或1")]
        public byte IsActive { get; set; }
    }
}